package br.com.massai.model.beans;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;

import br.com.massai.model.business.CollaboratorBusiness;
import br.com.massai.model.dao.AccessControlRepository;
import br.com.massai.model.entity.AccessControl;
import br.com.massai.model.entity.Action;
import br.com.massai.model.entity.Collaborator;
import br.com.massai.model.entity.Function;
import br.com.massai.model.entity.Url;
import br.com.massai.model.exceptions.ErrorCore;
import br.com.massai.model.exceptions.MessageCore;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.enums.Role;
import br.com.massai.view.utils.FacesUtil;
import br.com.massai.view.utils.MassaiUtil;

@LocalBean
@Stateless
@ManagedBean
public class SessionBean implements Serializable {

	private static final long serialVersionUID = 4362070683922361810L;

//	public static final String USER_LOGIN = "portal.userHandler";
//	public static final String FUNCTIONS_USER_LOGGEDIN = "portal.functionsUserLoggedIn";
//	public static final String ACTIONS_USER_LOGGEDIN = "portal.actionsUserLoggedIn";
//	public static final String PASS_CHANGE_PAGE = "/pages/user/passwordChange.xhtml";
//	public static final String HOME_PAGE = "/pages/home.xhtml";
//	public static final String ERROR_404_PAGE = "/error404.xhtml";
//	public static final String ERROR_500_PAGE = "/error500.xhtml";
//	public static final String INDEX_PAGE = "/index.xhtml";
	
	private Collaborator userLogged;

	private List<Url> listUrl;

	@EJB private CollaboratorBusiness collaboratorBusiness;
	@EJB private AccessControlRepository accessControlRepository;

	public SessionBean() {
		this.listUrl = new ArrayList<Url>();
	}

	public Collaborator getUserLoggedIn() {
//		HttpSession session = FacesUtil.obterSessao();
//		if(session != null)
//			return (Collaborator) FacesUtil.obterAtributoSessao(MassaiUtil.USER_LOGGED);
		return MassaiUtil.getUserLogged();
	}
	
//	public List<Function> getFunctionsByUser(){
//		List<Function> functions = new ArrayList<Function>();
//		if(getUserLoggedIn() != null)
//			for(Action a : getUserLoggedIn().getActions())
//				if(!functions.contains(a.getFunction()))
//					functions.add(a.getFunction());
//		return functions;
//	}
	
	public List<Action> getActionsByUser(){
		List<Action> actions = new ArrayList<Action>();
		if(getUserLoggedIn() != null)
			actions = getUserLoggedIn().getActions();
		return actions;
	}

	public List<Url> getUrlByUser() {
//		List<Url> urls = new ArrayList<Url>();
//		for(Function f : this.getFunctionsByUser()){
//			for(Url u : f.getUrls()){
//				if(!urls.contains(u))
//					urls.add(u);
//			}
//		}
//		return urls;
		return MassaiUtil.urlPermissions();
	}

	public void login(Collaborator collaborator) throws SystemException, IOException {
		try {
			Collaborator user = collaboratorBusiness.login(collaborator);
			if(user == null || user.getId() == null){
				user = new Collaborator();
				FacesUtil.registrarAviso(MessageCore.WARN_LOGIN_UNSUCESS.getCode());
				return;
			}

			user.setAccessControl(accessControlRepository.getLastAccessByUser(user));
			accessControlRepository.create(new AccessControl(FacesUtil.obterIp(), Calendar.getInstance().getTime(), user));

			this.userLogged = user;
			FacesUtil.adicionarAtributoSessao(MassaiUtil.USER_LOGGED, user);
			ExternalContext externalContext = FacesUtil.obterFacesContext().getExternalContext();
			externalContext.redirect(externalContext.getRequestContextPath() + "/pages/home.xhtml");

		} catch (SystemException e) {
			throw new SystemException(ErrorCore.ERROR_LOGIN, e);
		}
	}

	public void logout() throws SystemException, IOException {
		FacesUtil.obterResponse().sendRedirect("/portal/login.xhtml");
		FacesUtil.invalidarSessao();
	}

	public String getCollaboratorName(){
		if(getUserLoggedIn() != null)
			return getUserLoggedIn().getNameCollaborator();
		return "";
	}

	public boolean loggedIn(){
		return MassaiUtil.isLogIn();
	}

	public boolean showMenu(String function){
		if(this.getUserLoggedIn() != null && this.getUserLoggedIn().getRole().equals(Role.A)) 
			return true;

		List<Function> functions = MassaiUtil.functionsByUser();
		for(Function f : functions){
			if(f.getModule().getAcronym().equals(function))
				return true;
			else if(f.getAcronym().equals(function))
				return true;
		}
		return false;
	}
	
	public boolean showAction(String function, String action) {
		if(this.isAdmin()) return true;

		for(Action a : this.getActionsByUser()){
			if(a.getFunction().getAcronym().equals(function)){
				if(a.getAcronym().equals(action)){
					return true;
				}
			}
		}
		return false;
	}

	public String dateLastAccess(){
		Collaborator c = getUserLoggedIn();
		if(c != null && c.getAccessControl() != null)
			return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(c.getAccessControl().getLastAccess());
		return "Primeiro Acesso";
	}

	public String ipLastAccess(){
		Collaborator c = getUserLoggedIn();
		if(c != null && c.getAccessControl() != null)
			return c.getAccessControl().getLocationAccess();
		return FacesUtil.obterIp();
	}

	public boolean isAdmin(){
		if(this.getUserLoggedIn() != null && this.getUserLoggedIn().getRole().equals(Role.A))
			return true;
		return false;
	}

	@SuppressWarnings("unused")
	private void loadUrl() throws SystemException {
		//TODO carregar as URL permitidas ao usuário logado
	}

	public List<Url> getListUrl() {
		return this.listUrl;
	}

	public Collaborator getUserLogged() {
		return userLogged;
	}

	public void setUserLogged(Collaborator userLogged) {
		this.userLogged = userLogged;
	}
}
